package com.hemerasolutions.v2trainer.model.base;

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import javax.persistence.Column;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import com.hemerasolutions.v2trainer.model.unit.volume.VolumeFactor;

@MappedSuperclass
public class BaseValueHolder extends BaseModel {

	private static final long serialVersionUID = 1L;

	@Column
	protected double value;

    @ManyToOne
    protected VolumeFactor volumeFactor;
    
    public BaseValueHolder(){
    	super();
    }
    
	public double getValue() {
		if(this.volumeFactor != null && value != 0 ){
			EvaluationContext context 	= new StandardEvaluationContext(); 
			ExpressionParser parser 	= new SpelExpressionParser();
			Expression exp = null;

		
			context.setVariable("value", value);
			exp = parser.parseExpression( this.volumeFactor.getUpFormula());
			
			return (double) exp.getValue(context);
		}else{
			return value ;
			
		}
	}

	public void setValue(double value) {
		if(this.volumeFactor != null && value != 0 ){
			EvaluationContext context 	= new StandardEvaluationContext(); 
			ExpressionParser parser 	= new SpelExpressionParser();
			Expression exp = null;
			 
			context.setVariable("value", value);
			exp = parser.parseExpression( this.volumeFactor.getDownFormula());
			
			this.value = (double) exp.getValue(context);			
		}else{
			this.value = value  ;
		}
	}	
	
	public Date getDateValue() {

		Calendar c = Calendar.getInstance();
		c.setTimeZone(TimeZone.getTimeZone("Etc/GMT0"));

		if(value != 0){
			c.setTimeInMillis((long)this.getValue()*1000);
		}else{
			c.setTimeInMillis(0);
		}

		return c.getTime();
	}

	public void setDateValue(Date dateValue) {

		Calendar c = Calendar.getInstance();
		c.setTimeZone(TimeZone.getTimeZone("Etc/GMT0"));

		if(dateValue != null){
			c.setTime(dateValue);
			if(c.getTimeInMillis() == 0){
				this.value = 0;
			}else{
				this.setValue((double)c.getTimeInMillis()/1000);
			}
		}else{
			this.value = 0;
		}
	}

	public VolumeFactor getVolumeFactor() {
		return volumeFactor;
	}

	public void setVolumeFactor(VolumeFactor volumeFactor) {
		this.volumeFactor = volumeFactor;
	}
    

	
	
}
